package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Li_DaChiZi
 * Date: 2025/7/21
 * Time: 10:30
 */
public class TcpEchoServer {
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("启动服务器！");
        while (true) {
            Socket clientSocket =  serverSocket.accept();
            // 使用线程池的方法 (客户端发送一个请求后就快速断开连接了)
            ExecutorService service = Executors.newCachedThreadPool();
            service.submit(() -> {
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            // 创建线程的方式，来应对高并发多个客户端访问服务器
//            Thread t = new Thread(() -> {
//                try {
//                    processConnection(clientSocket);
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }
//            });
//            t.start();
        }
    }

    // 针对一个连接，提供处理逻辑
    private void processConnection(Socket clientSocket) throws IOException {
        //先打印一下客户端信息
        System.out.printf("[%s:%d] 客户端上线!]\n" ,clientSocket.getInetAddress(),clientSocket.getPort());
        // 获取到socket 中持有的流对象
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()){
            // 使用Scanner包装inputStream ， 就可以更方便的读取请求数据
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true) {
                // 1.读取请求并解析
                if (!scanner.hasNext()) {
                    // 如果 scanner 无法读取数据，说明客户端关闭了连接，导致服务器读取到了末尾
                    break;
                }
                String request = scanner.next();
                // 2.根据请求计算响应
                String response = process(request);
                // 3.把响应写回给客户端
                printWriter.println(response);
                printWriter.flush();

                // 4.打印日志
                System.out.printf("[%s:%d] req = %s; resp = %s\n", clientSocket.getInetAddress(),clientSocket.getPort(),request,response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.printf("[%s:%d] 客户端下线!]\n" ,clientSocket.getInetAddress(),clientSocket.getPort());
            clientSocket.close();
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
